package cycling.taxi.com.ui.activity;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ZoomControls;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

import cycling.taxi.com.IConstants;
import cycling.taxi.com.R;
import cycling.taxi.com.bean.HistoryInfo;
import cycling.taxi.com.bean.PositionInfo;
import cycling.taxi.com.parse.ParseTraject;
import cycling.taxi.com.person.ExitApplication;
import cycling.taxi.com.request.Config;
import cycling.taxi.com.request.RM;
import cycling.taxi.com.request.RequestBean;
import cycling.taxi.com.request.RequestCallback;
import cycling.taxi.com.request.RequestParams;
import cycling.taxi.com.request.RequestUtil;
import cycling.taxi.com.utils.LogUtil;
import cycling.taxi.com.utils.MD5Util;
import cycling.taxi.com.utils.SPUtil;
import cycling.taxi.com.utils.ToastUtil;
import cycling.taxi.com.utils.Urls;

/**
 * 轨迹
 */
public class TrajectoryActivity extends AppCompatActivity implements View.OnClickListener,RequestCallback {
   private ImageView back;
    private MapView mapView=null;
    private LocationClient mLocClient;

    /**
     * 是否第一次定位
     */
    private boolean isFirstLoc = true;// 是否第一次定位
    /**
     * 百度地图
     */
    private BaiduMap mBaiduMap;
    private TextView title_text;
    private String historyInfo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trajectory);
        Intent intent=getIntent();
        Bundle bundle=intent.getExtras();
        String str=bundle.getString("history");
        historyInfo=str;
       // historyInfo = new Gson().fromJson(str,HistoryInfo.class);
      //  ToastUtil.getInstance().toast(str);
        ExitApplication.getInstance().addActivity(this);
        initView();
    }

    private void initView() {
        mLocClient = new LocationClient(this);
        back= (ImageView) findViewById(R.id.back);
        title_text= (TextView) findViewById(R.id.title_text);
        title_text.setText("行车轨迹");
        mapView= (MapView) findViewById(R.id.bmapView);
        mBaiduMap=mapView.getMap();
        View child = mapView.getChildAt(1);
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)){
            child.setVisibility(View.INVISIBLE);
        }
        //地图上比例尺
        mapView.showScaleControl(false);
        // 隐藏缩放控件
        mapView.showZoomControls(false);
        //doGetCurrentPT();
        setListner();

        DrawTrajectory();
    }

    /**
     * 定位当前位置
     */
    private void doGetCurrentPT() {
        // 设置是否允许定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位服务的客户端。
        mLocClient = new LocationClient(this);
        // 注册定位监听函数
        mLocClient.registerLocationListener(new BDLocationListener() {

                                                @Override
                                                public void onReceiveLocation(BDLocation location) {
                                                    // map view 销毁后不在处理新接收的位置
                                                    if (location == null || mapView == null)
                                                        return;
                                                    // 定位数据:accuracy:定位精度,direction:GPS定位时方向角度.百度纬度坐标,百度经度坐标
                                                    MyLocationData locData = new MyLocationData.Builder()
                                                            .accuracy(location.getRadius())
                                                            // 此处设置开发者获取到的方向信息，顺时针0-360
                                                            .direction(100).latitude(location.getLatitude())
                                                            .longitude(location.getLongitude()).build();
                                                    // 设置定位数据, 只有先允许定位图层后设置数据才会生效
                                                    mBaiduMap.setMyLocationData(locData);
                                                    if (isFirstLoc) {
                                                        isFirstLoc = false;
                                                        LatLng ll = new LatLng(location.getLatitude(), location
                                                                .getLongitude());
                                                        // 设置地图新状态
                                                        MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                                                        // 改变地图状态
                                                        mBaiduMap.animateMapStatus(u);
                                                    }
                                                }
                                                public void onConnectHotSpotMessage(String arg0, int arg1) {
                                                }
                                            }

        );
        // 配置定位参数
        LocationClientOption option = new LocationClientOption();
        // 打开gps进行定位
        option.setOpenGps(true);// 打开gps
        // 设置坐标类型
        option.setCoorType("bd09ll"); // 设置坐标类型
        // 设置扫描间隔，单位是毫秒
        option.setScanSpan(1000);
        // 定位服务客户端设置配置
        mLocClient.setLocOption(option);
        // 定位服务开启
        mLocClient.start();
    }


    private void setListner() {
        back.setOnClickListener(this);

    }

    /**
     * 绘制轨迹
     */
    private void DrawTrajectory() {
        //获取服务器数据
        String mobile= SPUtil.getInstance().getData("phone");
        String password= SPUtil.getInstance().getData("password");
        RequestParams params = new RequestParams.Builder()
                .putParam("mobile",mobile)
                .putParam("password", MD5Util.MD5Encode(password))
                .putParam("beanJson",SPUtil.getInstance().getData("beanJson"))
                .putParam("history",historyInfo)
                .build();

        //开始请求发送数据到服务器服务器
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String url = Urls.getTrajectory();//轨迹的url路径

        RequestUtil.requestData(requestQueue,
                IConstants.TRAJECTORY,
                url,
                RM.GET,
                RequestBean.class,
                params,
                this);

    }
    public void onClick(View v) {
      if (v.getId() ==R.id.back){
          finish();
      }
    }

    // 实现地图的onResume()
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    // 实现地图的onPause()
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    // 实现地图的onDestroy()
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mBaiduMap.setMyLocationEnabled(false);
        mapView.onDestroy();
        mLocClient.stop();
        mBaiduMap.clear();

    }
    /**
     * 请求成功
     * @param bean
     * @param config
     */
    @Override
    public void requestSuccess(RequestBean bean, Config config) {
        LogUtil.e("requestSuccess数据="+bean.beanJson);
        try{
         //   ArrayList<PositionInfo> infos= ParseTraject.positionInfos(bean.beanJson.toString());
            ArrayList<PositionInfo> infos=new Gson().fromJson(bean.beanJson,new TypeToken<List<PositionInfo>>(){}.getType());
            // 根据资源 Id 创建 bitmap 描述信息
            BitmapDescriptor custom = BitmapDescriptorFactory.fromResource(R.layout.mancar_track_shape);
            // 经纬度集合
            List<LatLng> points = new ArrayList<>();
            List<Integer> index = new ArrayList<>();
            for (int i = 0; i < infos.size(); i++) {
                LatLng pt = new LatLng(infos.get(i).getLatitude(), infos.get(i).getLongitude());
                Log.e("tag",String.valueOf(infos.get(i).getLatitude())+String.valueOf(infos.get(i).getLatitude()));
                points.add(pt);
                if (i == infos.size() - 1) {
                    break;
                }
                if (i - 1 < 0) {
                    index.add(0);
                } else {
                    index.add(i - 1);
                }
            }
            /**
             * PolylineOptions：创建折线覆盖物选项类：width:设置折线线宽， 默认为 5， 单位：像素. color:颜色
             * points：设置折线坐标点列表。 customTexture：描述信息 textureIndex：顺序
             */
            OverlayOptions ooPolyline = new PolylineOptions().width(10)
                    .color(0xAAFF0000).points(points).customTexture(custom)
                    .textureIndex(index);
            // 向地图添加一个 Overlay
            mBaiduMap.addOverlay(ooPolyline);


            // OverlayOptions集合
            ArrayList<OverlayOptions> overlayList = new ArrayList<>();
            //开始点
            LatLng startPoint = new LatLng(infos.get(0).getLatitude(), infos.get(0).getLongitude());
            BitmapDescriptor startbitmap = BitmapDescriptorFactory.fromResource(R.drawable.ic_line_star_blue);
            OverlayOptions startOption = new MarkerOptions().position(startPoint).icon(startbitmap);
            overlayList.add(startOption);
            BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.kong);
            for(int i=1;i<infos.size()-1;i++){
                LatLng point = new LatLng(infos.get(i).getLatitude(), infos.get(i).getLongitude());
                OverlayOptions option = new MarkerOptions().position(point).icon(bitmap);
                overlayList.add(option);
            }
            //结束点
            LatLng endPoint = new LatLng(infos.get(infos.size()-1).getLatitude(), infos.get(infos.size()-1).getLongitude());
            BitmapDescriptor endbitmap = BitmapDescriptorFactory.fromResource(R.drawable.ic_line_stop_red);
            OverlayOptions endOption = new MarkerOptions().position(endPoint).icon(endbitmap);
            // 添加大结婚

            overlayList.add(endOption);
            // 定义点
            LatLng cenpt = new LatLng(infos.get(2).getLatitude(), infos.get(2).getLongitude());
            // 定义地图状态：target 地图操作的中心点。zoom:地图缩放级别 3~21
            MapStatus mMapStatus = new MapStatus.Builder().target(cenpt)
                    .zoom(15).build();
            // 设置地图新状态
            MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory
                    .newMapStatus(mMapStatus);
            // 改变地图状态
            mBaiduMap.setMapStatus(mMapStatusUpdate);
            // 向地图添加一个 Overlay
            mBaiduMap.addOverlays(overlayList);





        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 请求失败
     * @param bean
     * @param config
     */
    @Override
    public void requestFail(RequestBean bean, Config config) {
        LogUtil.e("失败");
        ToastUtil.getInstance().toast("查询轨迹失败");
        doGetCurrentPT();
    }

    /**
     * Token失效
     * @param requestTag
     * @param config
     */
    @Override
    public void requestTokenInvalid(String requestTag, Config config) {
        LogUtil.e("Token失效");
    }
}


